package cn.kpt.auth.controller;

import cn.kpt.auth.service.TokenService;
import cn.kpt.auth.service.UserService;
import cn.kpt.beans.pojo.ItripUser;
import cn.kpt.utils.EmptyUtils;
import cn.kpt.utils.MD5;
import org.springframework.web.bind.annotation.*;
import weibo4j.Oauth;
import weibo4j.Users;
import weibo4j.http.AccessToken;
import weibo4j.model.User;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * @version 1.0
 * @ClassName ThirdLoginContrloller
 * @Description TODO 功能待完善，实现微博接入基本演示
 * @Author kangpengtao
 * @Date 2019/10/1 1:16
 */
@RestController
@RequestMapping("/vendors")
public class ThirdLoginContrloller {

//    Oauth2.0授权协议
    private Oauth oauth = new Oauth();
    @Resource
    private UserService userService;
    @Resource
    private TokenService tokenService;
    /**
     * 页面跳转至登录页
     */
    @RequestMapping(value = "/sina/login", method = RequestMethod.GET)
    public void sinalogin(HttpServletResponse response){
        try {
            //获取请求地址
            String code = oauth.authorize("code");
            //发起请求获取code
            response.sendRedirect(code);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取用户信息，进行注册或者登录
     */
    @RequestMapping(value = "/sina/callback", method = RequestMethod.GET)
    public void sinaCallback(@RequestParam String code, @RequestHeader("User-Agent") String userAgent, HttpServletResponse response){
        try {
            //根据code获得AccessToken对象
            AccessToken accessToken = oauth.getAccessTokenByCode(code);
            //获取用户信息
            Users users = new Users(accessToken.getAccessToken());
            User user = users.showUserById(accessToken.getUid());
            //判断用户是否已经注册
            ItripUser itripUser = userService.checkUserByOpenId(user.getId());
            if (EmptyUtils.isEmpty(itripUser.getWeibo())) {
                // 进行注册
                itripUser.setUserCode(user.getId());
                itripUser.setUserName(user.getScreenName());
                itripUser.setUserPassword(MD5.getMd5(user.getId(), 16));
                itripUser.setWeibo(user.getId());
                itripUser.setFlatID(Long.valueOf(user.getId()));
                itripUser.setUserType(3); // 微博
                userService.registerThirdUser(itripUser);
            }
            // 使用Token存储用户信息
            String token = tokenService.genToken(itripUser, userAgent);
            // 保存Token 帐号登录互斥更换旧信息
            tokenService.saveToken(token, itripUser, userAgent);
            // 通过地址栏将信息返回给前端
            StringBuilder loginPage = new StringBuilder();
            loginPage.append("http://www.itrip.335.cn/#/login");
            loginPage.append("?user_type=1&token=" + token);
            loginPage.append("&access_token=" + accessToken.getAccessToken());
            loginPage.append("&expires_in=" + accessToken.getExpireIn());
            loginPage.append("&refresh_token=" + accessToken.getRefreshToken());
            loginPage.append("&openid=" + accessToken.getUid());
            response.sendRedirect(loginPage.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
